const ColorConverter = require('../../../utils/color');

Page({
  data: {
    currentTab: 'converter',
    tabs: [
      { key: 'converter', name: '颜色转换' },
      { key: 'palette', name: '调色板' },
      { key: 'picker', name: '取色器' }
    ],
    
    // 颜色转换
    hexValue: '#3498db',
    rgbR: 52,
    rgbG: 152,
    rgbB: 219,
    hslH: 204,
    hslS: 70,
    hslL: 53,
    
    // 调色板
    baseColor: '#3498db',
    paletteType: 'monochromatic',
    paletteTypes: [
      { key: 'monochromatic', name: '单色调' },
      { key: 'complementary', name: '互补色' },
      { key: 'triadic', name: '三角色' },
      { key: 'analogous', name: '类似色' },
      { key: 'tetradic', name: '四角色' }
    ],
    generatedPalette: [],
    
    // 取色器
    pickedColors: [],
    
    // 历史记录
    colorHistory: []
  },

  onLoad() {
    this.colorConverter = new ColorConverter();
    this.updateAllFormats();
    this.generatePalette();
    this.loadHistory();
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
  },

  // HEX输入
  onHexInput(e) {
    let hex = e.detail.value;
    if (!hex.startsWith('#')) {
      hex = '#' + hex;
    }
    
    this.setData({ hexValue: hex });
    
    if (this.isValidHex(hex)) {
      const rgb = this.colorConverter.hexToRgb(hex);
      if (rgb) {
        const hsl = this.colorConverter.rgbToHsl(rgb.r, rgb.g, rgb.b);
        this.setData({
          rgbR: rgb.r,
          rgbG: rgb.g,
          rgbB: rgb.b,
          hslH: hsl.h,
          hslS: hsl.s,
          hslL: hsl.l
        });
        this.addToHistory(hex);
      }
    }
  },

  // RGB输入
  onRgbInput(e) {
    const type = e.currentTarget.dataset.type;
    const value = Math.max(0, Math.min(255, parseInt(e.detail.value) || 0));
    
    const updateData = {};
    updateData[`rgb${type.toUpperCase()}`] = value;
    this.setData(updateData);
    
    const { rgbR, rgbG, rgbB } = this.data;
    const r = type === 'r' ? value : rgbR;
    const g = type === 'g' ? value : rgbG;
    const b = type === 'b' ? value : rgbB;
    
    const hex = this.colorConverter.rgbToHex(r, g, b);
    const hsl = this.colorConverter.rgbToHsl(r, g, b);
    
    this.setData({
      hexValue: hex,
      hslH: hsl.h,
      hslS: hsl.s,
      hslL: hsl.l
    });
    
    this.addToHistory(hex);
  },

  // HSL输入
  onHslInput(e) {
    const type = e.currentTarget.dataset.type;
    let value = parseInt(e.detail.value) || 0;
    
    if (type === 'h') {
      value = Math.max(0, Math.min(360, value));
    } else {
      value = Math.max(0, Math.min(100, value));
    }
    
    const updateData = {};
    updateData[`hsl${type.toUpperCase()}`] = value;
    this.setData(updateData);
    
    const { hslH, hslS, hslL } = this.data;
    const h = type === 'h' ? value : hslH;
    const s = type === 's' ? value : hslS;
    const l = type === 'l' ? value : hslL;
    
    const rgb = this.colorConverter.hslToRgb(h, s, l);
    const hex = this.colorConverter.rgbToHex(rgb.r, rgb.g, rgb.b);
    
    this.setData({
      hexValue: hex,
      rgbR: rgb.r,
      rgbG: rgb.g,
      rgbB: rgb.b
    });
    
    this.addToHistory(hex);
  },

  // 更新所有格式
  updateAllFormats() {
    const { hexValue } = this.data;
    if (this.isValidHex(hexValue)) {
      const rgb = this.colorConverter.hexToRgb(hexValue);
      if (rgb) {
        const hsl = this.colorConverter.rgbToHsl(rgb.r, rgb.g, rgb.b);
        this.setData({
          rgbR: rgb.r,
          rgbG: rgb.g,
          rgbB: rgb.b,
          hslH: hsl.h,
          hslS: hsl.s,
          hslL: hsl.l
        });
      }
    }
  },

  // 验证HEX格式
  isValidHex(hex) {
    return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex);
  },

  // 随机颜色
  randomColor() {
    const hex = '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
    this.setData({ hexValue: hex });
    this.updateAllFormats();
    this.addToHistory(hex);
  },

  // 复制颜色值
  copyColor(e) {
    const format = e.currentTarget.dataset.format;
    let value = '';
    
    switch (format) {
      case 'hex':
        value = this.data.hexValue;
        break;
      case 'rgb':
        value = `rgb(${this.data.rgbR}, ${this.data.rgbG}, ${this.data.rgbB})`;
        break;
      case 'hsl':
        value = `hsl(${this.data.hslH}, ${this.data.hslS}%, ${this.data.hslL}%)`;
        break;
    }
    
    wx.setClipboardData({
      data: value,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        });
      }
    });
  },

  // 调色板相关
  onBaseColorInput(e) {
    let color = e.detail.value;
    if (!color.startsWith('#')) {
      color = '#' + color;
    }
    
    this.setData({ baseColor: color });
    if (this.isValidHex(color)) {
      this.generatePalette();
    }
  },

  // 选择调色板类型
  selectPaletteType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ paletteType: type });
    this.generatePalette();
  },

  // 生成调色板
  generatePalette() {
    const { baseColor, paletteType } = this.data;
    if (!this.isValidHex(baseColor)) return;
    
    const palette = this.colorConverter.generatePalette(baseColor, paletteType);
    this.setData({ generatedPalette: palette });
  },

  // 使用调色板颜色
  usePaletteColor(e) {
    const color = e.currentTarget.dataset.color;
    this.setData({
      hexValue: color,
      currentTab: 'converter'
    });
    this.updateAllFormats();
    this.addToHistory(color);
  },

  // 复制调色板
  copyPalette() {
    const colors = this.data.generatedPalette.join(', ');
    wx.setClipboardData({
      data: colors,
      success: () => {
        wx.showToast({
          title: '调色板已复制',
          icon: 'success'
        });
      }
    });
  },

  // 从图片取色
  pickFromImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.analyzeImageColors(tempFilePath);
      }
    });
  },

  // 分析图片颜色
  analyzeImageColors(imagePath) {
    // 创建canvas来分析图片
    const query = wx.createSelectorQuery();
    query.select('#color-canvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        // 设置canvas尺寸
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = 100 * dpr;
        canvas.height = 100 * dpr;
        ctx.scale(dpr, dpr);
        
        // 创建图片对象
        const img = canvas.createImage();
        img.onload = () => {
          ctx.drawImage(img, 0, 0, 100, 100);
          
          // 提取主要颜色
          const colors = this.extractDominantColors(ctx, 100, 100);
          this.setData({ pickedColors: colors });
        };
        img.src = imagePath;
      });
  },

  // 提取主要颜色
  extractDominantColors(ctx, width, height) {
    const imageData = ctx.getImageData(0, 0, width, height);
    const data = imageData.data;
    const colorMap = new Map();
    
    // 采样像素点
    for (let i = 0; i < data.length; i += 16) { // 每4个像素采样一次
      const r = data[i];
      const g = data[i + 1];
      const b = data[i + 2];
      const a = data[i + 3];
      
      if (a > 128) { // 忽略透明像素
        // 量化颜色以减少颜色数量
        const quantizedR = Math.floor(r / 32) * 32;
        const quantizedG = Math.floor(g / 32) * 32;
        const quantizedB = Math.floor(b / 32) * 32;
        
        const hex = this.colorConverter.rgbToHex(quantizedR, quantizedG, quantizedB);
        colorMap.set(hex, (colorMap.get(hex) || 0) + 1);
      }
    }
    
    // 按出现频率排序，取前8个颜色
    return Array.from(colorMap.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, 8)
      .map(([color]) => color);
  },

  // 使用提取的颜色
  usePickedColor(e) {
    const color = e.currentTarget.dataset.color;
    this.setData({
      hexValue: color,
      currentTab: 'converter'
    });
    this.updateAllFormats();
    this.addToHistory(color);
  },

  // 历史记录相关
  addToHistory(color) {
    let history = this.data.colorHistory;
    
    // 移除重复颜色
    history = history.filter(c => c !== color);
    
    // 添加到开头
    history.unshift(color);
    
    // 最多保存20个颜色
    if (history.length > 20) {
      history = history.slice(0, 20);
    }
    
    this.setData({ colorHistory: history });
    this.saveHistory();
  },

  // 使用历史颜色
  useHistoryColor(e) {
    const color = e.currentTarget.dataset.color;
    this.setData({ hexValue: color });
    this.updateAllFormats();
  },

  // 清除历史记录
  clearHistory() {
    this.setData({ colorHistory: [] });
    this.saveHistory();
    wx.showToast({
      title: '历史记录已清除',
      icon: 'success'
    });
  },

  // 保存历史记录
  saveHistory() {
    wx.setStorageSync('color_history', this.data.colorHistory);
  },

  // 加载历史记录
  loadHistory() {
    const history = wx.getStorageSync('color_history') || [];
    this.setData({ colorHistory: history });
  },

  // 颜色对比度检查
  checkContrast() {
    const { hexValue } = this.data;
    const rgb = this.colorConverter.hexToRgb(hexValue);
    
    if (rgb) {
      const luminance = this.colorConverter.getLuminance(rgb.r, rgb.g, rgb.b);
      const contrastWithWhite = this.colorConverter.getContrastRatio(luminance, 1);
      const contrastWithBlack = this.colorConverter.getContrastRatio(luminance, 0);
      
      wx.showModal({
        title: '颜色对比度',
        content: `与白色对比度: ${contrastWithWhite.toFixed(2)}\n与黑色对比度: ${contrastWithBlack.toFixed(2)}\n\nWCAG AA标准: 4.5:1\nWCAG AAA标准: 7:1`,
        showCancel: false
      });
    }
  }
});